package thread2;

/**
 * Created with IntelliJ IDEA.
 * Description:锁
 * User: bjc
 * Date: 2025-08-18
 * Time: 20:17
 */
public class ThreadDemo1 {
    private static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        //创建一个对象
        Object locker = new Object();

        //创建两个线程，每个线程对count加5W次
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                synchronized (locker) {
                    count++;
                }
            }
        },"t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                synchronized (locker) {
                    count++;
                }
            }
        },"t2");
        t1.start();
        t2.start();

        t1.join(); //等待t1执行完毕
        t2.join();//等待t2执行完毕
        //正确结果应该是10W
        System.out.println("count = " + count);
    }
}
